﻿const express = require('express'),
  router = express.Router(),
    user = require("../model/user"),
    util=require("../util/util"),
    crypto = require('crypto'),
    tokenTtl = require("../model/tokenttl"),
    roleauth = require("../model/roleauth"),
    // jwt= require('jsonwebtoken'),
    // secret = 'salt',
  captcha = require('trek-captcha');

//获取图片验证码
async function getImgCode(req, res) {
    const {token, buffer} = await captcha();
    req.session.captcha = token;
    res.writeHead(200, {'Content-Type': 'image/png'});
    res.write(buffer);
    res.end();
}

/**
 * @function 用户身份验证
 * @author yelin
 * @date 2017-05-19
 * @param username,status,
 */
router.post('/checklogin', function (req, res) {
    const objdata = {}
    const params = {
        uname: req.body.username,
    }
    var pwd = req.body.password
    user.find(params, (err,results)=> {
        if(err){
            res.send(util.reObj(-1,'failed',err))
        }else {
            if(results.length>0){
                let salt=util.randomString(8)
                let upwd=util.randomString(32)
                if(results[0].upwd)
                {
                    salt = results[0].upwd.substring(0, 8)
                    upwd=results[0].upwd.substring(8)
                }
                let password = crypto.createHash('md5').update(pwd + salt).digest('hex');
                if (password.toString() == upwd) {
                    let timestamp=new Date().getTime()
                    tokenTtl.findOneAndUpdate(params ,{createdAt:timestamp}, null, function(err,response){
                        if(!err&&response)
                        {
                            res.send(util.reObj(0,'用户身份验证成功',response))
                        }
                        else
                        {
                            const tokenObj = new tokenTtl({ uname: req.body.username,token:util.randomString(32)});
                            tokenObj.save().then(results => res.send(util.reObj(0,'用户身份验证成功',results))).catch((err) => res.send(util.reObj(-1,'用户身份验证失败',err)));
                        }
                    })

                }
                else
                {
                    res.send(util.reObj(-1, '无效的密码', []))
                }

            }else{
                res.send(util.reObj(-1,'用户身份验证失败',err))
            }
        }
    })

})

/*返回浏览器cookie*/
router.get('/cookie', (req, res) => {
  //res.setHeader('Content-Type', 'text/html');
  //res.json(req.cookies.userinfo)
  res.send(req.cookies.userinfo)
});



router.get('/getImg', function (req, res, next) {
  getImgCode(req, res);
})

//核对验证码
router.get('/checkCaptcha', function (req, res) {
  var captcha = req.query.captcha;
  if (req.session.captcha == captcha) {
    res.send('success');
  } else {
    res.send('验证码错误');
  }
})

router.all('/getheaders',function (req,res) {
console.log('headers:'+req.headers)
    res.send('hahaha')
})

module.exports = router;
